package user

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/tools/ent/hzusersurvey"
	"private-domain-overseas-service/tools/ent/predicate"

	"private-domain-overseas-service/tools/ent"
)

type UserSurveyDao struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserSurveyDao(ctx context.Context, svcCtx *svc.ServiceContext) *UserSurveyDao {
	return &UserSurveyDao{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// UserSurveyCreate - 添加问卷邀请
func (l *UserSurveyDao) UserSurveyCreate(survey *ent.HzUserSurvey, tx *ent.Tx) error {
	clientDao := l.svcCtx.Orm.HzUserSurvey
	if tx != nil {
		clientDao = tx.HzUserSurvey
	}
	err := clientDao.Create().
		SetUserSurveyName(survey.UserSurveyName).
		SetUserSurveyPhone(survey.UserSurveyPhone).
		SetUserSurveySex(survey.UserSurveySex).
		SetUserSurveyOrderNum(survey.UserSurveyOrderNum).
		SetUserSurveyType(survey.UserSurveyType).
		SetCreatedAt(survey.CreatedAt).
		SetUpdateAt(survey.UpdateAt).
		Exec(l.ctx)
	if err != nil {
		return err
	}
	return nil
}

// UserSurveyUpdate - 修改问卷邀请
func (l *UserSurveyDao) UserSurveyUpdate(survey *ent.HzUserSurvey, tx *ent.Tx) error {
	clientDao := l.svcCtx.Orm.HzUserSurvey
	if tx != nil {
		clientDao = tx.HzUserSurvey
	}
	err := clientDao.UpdateOneID(survey.ID).
		SetUserSurveyName(survey.UserSurveyName).
		SetUserSurveyPhone(survey.UserSurveyPhone).
		SetUserSurveySex(survey.UserSurveySex).
		SetUserSurveyOrderNum(survey.UserSurveyOrderNum).
		SetUserSurveyType(survey.UserSurveyType).
		SetUpdateAt(survey.UpdateAt).
		Exec(l.ctx)
	if err != nil {
		return err
	}
	return nil
}

// UserSurveyDaoConditionsFirst - 根据条件查询单条用户问卷
func (l *UserSurveyDao) UserSurveyDaoConditionsFirst(conditions []predicate.HzUserSurvey) (*ent.HzUserSurvey, error) {
	survey, err := l.svcCtx.Orm.HzUserSurvey.Query().
		Where(conditions...).
		First(l.ctx)
	if err != nil {
		return nil, err
	}
	return survey, nil
}

// UserSurveyConditionsAllByPage - 分页查询用户问卷信息
func (l *UserSurveyDao) UserSurveyConditionsAllByPage(conditions []predicate.HzUserSurvey, current, pageSize int64) ([]*ent.HzUserSurvey, int64, error) {
	query := l.svcCtx.Orm.HzUserSurvey.Query().Where(conditions...)

	total, err := query.Count(l.ctx)
	if err != nil {
		return nil, 0, err
	}

	records, err := query.
		Offset(int((current - 1) * pageSize)).
		Order(ent.Desc(hzusersurvey.FieldID)).
		Limit(int(pageSize)).
		All(l.ctx)
	if err != nil {
		return nil, 0, err
	}

	return records, int64(total), nil

}
